# models/package_info.py - 包信息模型
from typing import Dict, Any, List
from datetime import datetime
from .file_version import FileVersion

class PackageInfo:
    """包完整信息模型（包含版本信息）"""
    
    def __init__(self, name: str, brief: str = "", description: str = "", 
                 preview_image: str = "preview.png"):
        self.name = name
        self.brief = brief
        self.description = description
        self.preview_image = preview_image
        self.created_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        self.updated_time = self.created_time
        self.current_version = ""
        self.versions: Dict[str, FileVersion] = {}
    
    def add_version(self, version: FileVersion):
        """添加版本"""
        self.versions[version.version] = version
        self.current_version = version.version
        self.updated_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    def update_version(self, version: str, brief: str = None, description: str = None):
        """更新版本信息"""
        if version in self.versions:
            if brief is not None:
                self.versions[version].brief = brief
            if description is not None:
                self.versions[version].description = description
            self.updated_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        versions_dict = {}
        for version, version_info in self.versions.items():
            versions_dict[version] = version_info.to_dict()
        
        return {
            "name": self.name,
            "brief": self.brief,
            "description": self.description,
            "preview_image": self.preview_image,
            "created_time": self.created_time,
            "updated_time": self.updated_time,
            "current_version": self.current_version,
            "versions": versions_dict
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'PackageInfo':
        """从字典创建实例"""
        instance = cls(
            name=data.get("name", ""),
            brief=data.get("brief", ""),
            description=data.get("description", ""),
            preview_image=data.get("preview_image", "preview.png")
        )
        instance.created_time = data.get("created_time", instance.created_time)
        instance.updated_time = data.get("updated_time", instance.updated_time)
        instance.current_version = data.get("current_version", "")
        
        # 加载版本信息
        versions_data = data.get("versions", {})
        for version, version_data in versions_data.items():
            version_obj = FileVersion.from_dict(version_data)
            instance.versions[version] = version_obj
        
        return instance
    
    def get_version_list(self) -> List[str]:
        """获取版本列表"""
        return list(self.versions.keys())